mod db;
mod errors;
mod handlers;
mod models;
mod util;
use crate::util::load_config;
use actix_web::{web, App, HttpServer};
use handlers::{add_todo_item, get_todo_item_by_id, get_todo_items, update_todo_item};
use sqlx::postgres::PgPoolOptions;
use std::io;

#[actix_web::main]
async fn main() -> io::Result<()> {
    // 设置数据库连接池
    let app_config = load_config().expect("加载配置数据失败");
    println!("app_config pg_addr:{}", &app_config.pgaddr);
    let db_pool = PgPoolOptions::new()
        .max_connections(5)
        .connect(&app_config.pgaddr)
        .await
        .expect("连接数据库失败");

    println!("db connected");
    // 启动HTTP服务器
    HttpServer::new(move || {
        App::new()
            .app_data(web::Data::new(db_pool.clone())) // 将数据库连接池添加到应用程序的数据中
            .route("/api/todo", web::post().to(add_todo_item))
            .route("/api/todo", web::put().to(update_todo_item))
            .route("/api/todo/list/{owner_key}", web::get().to(get_todo_items))
            .route("/api/todo/{id}", web::get().to(get_todo_item_by_id))
    })
    .bind(&app_config.serveraddr)?
    .run()
    .await
}
